import { getPosIDs, getUserDutyDepID, getPosName, getUserID, getUserName, getDeptPosTreeIcon, getLevelZero, getTenantID, getCompanyID } from '@/utils';
import { Empty, message, Spin } from 'antd';
import { useContext, useEffect, useImperativeHandle, useMemo, useState } from 'react';
import { WorkflowSwitchContext } from '../common';
import { getTaskNodes, procdefDataGridServices, getPosTreeService } from '../services';
import { WorkflowNodesTable } from './WorkflowNodesTable';
import _ from 'lodash';
import React from 'react';
import { WorkflowSwitchAPI } from '../common/type';
import { getPersonalInfo } from '@/utils/authority';
import { ILoadMapTypeAll } from '@/common';

export const WorkflowNodesView = React.forwardRef<WorkflowSwitchAPI.IWorkflowNodesViewRef, WorkflowSwitchAPI.IWorkflowNodesView>(
  (
    {
      switchFlowObj, //选中的非默认流程 id
      changeProcessID, //保存当前展示的默认流程 id  给查看流程图使用
      loadUserRun,
      loadUserData,
      loadUserLoading,
      setFlowNodesLoading,
    },
    ref,
  ) => {
    const { requestController, orderType, category, businessCategory, businessInfoObj, workFlowName } = useContext(WorkflowSwitchContext);

    /** 保存 节点之间的数据 */
    const [workFlowNodes, setWorkFlowNodes] = useState<Record<string, any>[]>([]);

    /**
     * 处理节点间用户数据会签和普通
     */
    const handNodeUserList = (dealerKey: string[], dealerName: string[], dealerType: number) => {
      let allList: Record<string, any>[] = [];
      let obj: Record<string, any> = {};
      dealerKey?.forEach((itemKey: any, index: number) => {
        let [postKey, userKey]: string[] = itemKey?.split('|');
        let [postName, userName]: string[] = dealerName?.[index]?.split('|');
        if (dealerType == 0) {
          const objLabelKey: string = `${postKey}_${postName}`;
          let userObj: Record<string, any> = {
            userID: userKey,
            userName: userName,
          };
          obj[objLabelKey] = obj?.[objLabelKey] ? [...obj[objLabelKey], userObj] : [userObj];
        } else if (dealerType == 1) {
          let [postKey, userKey]: string[] = itemKey?.split('|');
          let [postName, userName]: string[] = dealerName?.[index]?.split('|');
          let obj: Record<string, any> = {
            postId: postKey,
            postName: postName,
            defaultDealer: userKey,
            defaultDealerName: userName,
          };
          allList?.push(obj);
        }
      });

      if (obj && JSON.stringify(obj) != '{}' && dealerType == 0) {
        Object.keys(obj)?.forEach((posItem: any, posIndex: number) => {
          const [postId, postName]: string[] = posItem?.split('_');
          let newObj: Record<string, any> = {
            postId,
            postName,
            defaultDealer: obj?.[posItem]?.[0]?.userID,
            defaultDealerName: obj?.[posItem]?.[0]?.userName,
            userList: obj?.[posItem],
          };

          allList?.push(newObj);
        });
      }
      return allList;
    };

    /**格式化岗位树数据 */
    const handleNotPostion = (treeData: Record<string, any>[]) => {
      const loopTree = (dataList: Record<string, any>[]) => {
        dataList?.forEach((item: any, index: number) => {
          if (item?.textType == '0' || item?.textType == '1' || item?.textType == '2') {
            const childrenList: Record<string, any>[] = item?.children?.filter(
              (itemChil: any) => itemChil?.textType == '0' || itemChil?.textType == '1' || itemChil?.textType == '2',
            );
            dataList[index] = {
              ...item,
              title: (
                <span>
                  {getDeptPosTreeIcon(String(item?.textType))}
                  {item?.text}
                </span>
              ),
              children: childrenList?.length > 0 ? loopTree(childrenList) : null,
              disabled: item?.textType == '2' ? false : true,
            };
          }
        });
        return dataList;
      };

      const treeList: Record<string, any>[] = loopTree(treeData);
      return treeList;
    };

    /**岗位数据回调 */
    const getPosTreeCallback = (res) => {
      if (res?.obj) {
        const result = handleNotPostion(res.obj);
        if (res.obj[0] && res.obj[0].id == getPosIDs()) setOwnPosList(result);
        if (res.obj[0] && res.obj[0].id == businessInfoObj.busiDepartmentID) setBusPosList(result);
        if (res.obj[0] && res.obj[0].id == businessInfoObj.relateDepartmentID) setRelPosList(result);
        if (res.obj[0] && res.obj[0].id == getCompanyID()) setTheCompanyPosList(result);
        if (res.obj[0] && res.obj[0].id == 1) setBusinessPosList(result);
        /**资产中 */
        if (category?.indexOf(`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}`) > -1) {
          if (res.obj[0] && res.obj[0].id == businessInfoObj.newDepartmentID) setRelAssetDepartmentPosList(result);
          if (res.obj[0] && res.obj[0].id == businessInfoObj.originalStoreCompanyID) setRelAssetOriginalPosList(result);
          if (res.obj[0] && res.obj[0].id == businessInfoObj.newStoreDepartmentID) setNewStoreDepartmentPosList(result);
          if (res.obj[0] && res.obj[0].id == businessInfoObj.originalStoreDepartmentID) setOriginStoreDepartmentPosList(result);
          if (res.obj[0] && res.obj[0].id == businessInfoObj.belongDepartmentID) setBelongDepartmentPosList(result);
        }
        /**采购 */
        if (businessCategory?.indexOf(`${getTenantID()}${ILoadMapTypeAll.PURAPPLY_APPLY}`) > -1) {
          if (res.obj[0] && res.obj[0].id == businessInfoObj.consignDepartmentID) setConsignDepartmentPosList(result);
          if (res.obj[0] && res.obj[0].id == businessInfoObj.platformDepartmentID) setPlatformDepartmentPosList(result);
        }
      }
    };
    const getOwnPosTreeCallback = (res) => {
      if (res?.obj) {
        const result = handleNotPostion(res.obj);
        if (res.obj[0]) setOwnPosList(result);
      }
    };

    const getDutyPosTreeCallback = (res) => {
      if (res?.obj) {
        const result = handleNotPostion(res.obj);
        if (res.obj[0]) setDutyDepartList(result);
      }
    };

    /**获取岗位树 */
    const { getPosTreeRun } = getPosTreeService(getPosTreeCallback);
    const { getOwnPosTreeRun } = getPosTreeService(getOwnPosTreeCallback);
    const { getBusPosTreeRun } = getPosTreeService(getPosTreeCallback);
    const { getDutyPosTreeRun } = getPosTreeService(getDutyPosTreeCallback);
    const { getBUPosTreeRun } = getPosTreeService(getPosTreeCallback);
    const { getTheCompanyPosTreeRun } = getPosTreeService(getPosTreeCallback);

    /**资产中获取岗位树 */
    const { getAssetDepartmentPosTreeRun } = getPosTreeService(getPosTreeCallback);
    const { getAssetOriginalPosTreeRun } = getPosTreeService(getPosTreeCallback);
    const { getNewStoreDepartmentPosTreeRun } = getPosTreeService(getPosTreeCallback);
    const { getOriginalStoreDepartmentPosTreeRun } = getPosTreeService(getPosTreeCallback);
    const { getBelongDepartmentPosTreeRun } = getPosTreeService(getPosTreeCallback);

    /**采购      consignDepartmentID  platformDepartmentID */
    const { getConsignDepartmentPosTreeRun } = getPosTreeService(getPosTreeCallback); //职能 业务归口部门专责审核 + 业务归口部门领导审批
    const { getPlatformDepartmentPosTreeRun } = getPosTreeService(getPosTreeCallback); //科研 平台归口管理部门审批 + 平台归口管理部门领导审批

    /**
     * 处理每个节点的岗位数据
     * @param nodeInfoObj
     * @returns
     */
    const handlePostList = (nodeInfoObj: Record<string, any>, nodeInfoIndex: number) => {
      const postKeyList: string[] = nodeInfoObj?.dealPositionID ? nodeInfoObj?.dealPositionID?.split(',')?.filter((itemKey: any) => itemKey) : [];
      // const postKeyListName: string[] = nodeInfoObj?.dealPositionName ? nodeInfoObj?.dealPositionName?.split(',')?.filter((itemName: any) => itemName) : [];

      let postDateList: Record<string, any>[] = []; //存储节点岗位数据

      let postDateKeys: string[] | any = []; //存储节点 岗位 id
      let newUserList: string[] | any = []; //存储节点 用户 id
      let posTreeData: any = []; //存储岗位机构树

      if (nodeInfoObj?.dealPositionID == 'originPositionID,') {
        let postList: Record<string, any> = {
          postId: getPosIDs(),
          postName: getPosName(),
          defaultDealer: getUserID(),
          defaultDealerName: getUserName(),
        };
        postDateList?.push(postList);
        postDateKeys?.push(getPosIDs());
      } else {
        /**
         * 获取到处理人的数据
         */
        let userListKey: string[] = nodeInfoObj?.postDealerID ? nodeInfoObj?.postDealerID?.split(',')?.filter((itemUserKey: any) => itemUserKey) : [];
        let userListName: string[] = nodeInfoObj?.postDealerName ? nodeInfoObj?.postDealerName?.split(',')?.filter((itemUserName: any) => itemUserName) : [];

        newUserList = handNodeUserList(userListKey, userListName, nodeInfoObj?.taskIsSign);

        postDateList?.push(...newUserList);
        postDateKeys = [...postDateKeys, ...postKeyList];
      }

      /**根据任务名称判断是否需要获取岗位树数据 */
      if (getPosList(nodeInfoObj?.taskName)) posTreeData = getPosList(nodeInfoObj?.taskName);

      return {
        postDateList,
        postDateKeys,
        newUserList,
        posTreeData,
      };
    };

    const getPosList = (taskName) => {
      /**采购 */
      if (businessCategory?.indexOf(`${getTenantID()}${ILoadMapTypeAll.PURAPPLY_APPLY}`) > -1) {
        /**职能 */
        if (taskName.indexOf('业务归口部门') > -1) {
          return consignDepartmentPosList;
        }
        if (taskName.indexOf('中心财务部审批') > -1 || taskName.indexOf('中心领导审批') > -1) {
          return theCompanyPosList;
        }
        /**科研 */
        if (taskName.indexOf('平台归口部门') > -1) {
          return platformDepartmentPosList;
        }

        if (
          taskName.indexOf('实验室财务部') > -1 ||
          taskName.indexOf('招采中心领导审核') > -1 ||
          taskName.indexOf('实验室分管领导审批') > -1 ||
          taskName.indexOf('实验室科创部专责审核') > -1 ||
          taskName.indexOf('实验室科创部领导审核') > -1
        ) {
          return businessPosList;
        }
      }

      /***
       * 资产交接"100199031012"
       */
      if (businessInfoObj?.businessType == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1012`) {
        if (taskName.indexOf('移交方部门/团队资管员审批') >= 0 || taskName.indexOf('移交方部门/团队领导审批') >= 0) {
          return dutyDepartList;
        }
        if (taskName.indexOf('接收方部门/团队资管员审批') >= 0 || taskName.indexOf('接收方部门/团队领导审批') >= 0) {
          return relAssetDepartmentPosList;
        }
      }

      /***
       * 入库登记""
       */
      if (businessInfoObj?.businessType == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1020`) {
        if (taskName.indexOf('部门/团队仓管员入库') >= 0) {
          return dutyDepartList;
        }
      }

      /***
       * 领用
       */
      if (businessInfoObj?.businessType == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1011`) {
        if (taskName.indexOf('部门/团队仓管员出库') >= 0) {
          //belongDepartmentID
          return belongDepartmentPosList;
        }
      }

      /***
       * 退库
       */
      if (businessInfoObj?.businessType == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1013`) {
        if (taskName.indexOf('部门/团队仓管员入库') >= 0) {
          //belongDepartmentID
          return belongDepartmentPosList;
        }
      }

      // /***
      //  * 调剂"100199031015"   已修改
      //  */
      // if (businessInfoObj?.businessType == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1015`) {
      //   if (taskName.indexOf('接收方资产部专责审批') >= 0 || taskName.indexOf('接收方部门/团队领导审批') >= 0) {
      //     return dutyDepartList;
      //   }
      //   if (taskName.indexOf('移交方资产部专责审批') >= 0 || taskName.indexOf('移交方部门/团队领导审批') >= 0) {
      //     return relAssetOriginalPosList;
      //   }
      // }

      /***
       * 调剂"100199031015"
       */
      if (businessInfoObj?.businessType == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1015`) {
        if (taskName.indexOf('接收方资产部专责审批') >= 0) {
          return dutyDepartList;
        }
        // if (taskName.indexOf('财务资产部专责复核') >= 0) {
        //   return dutyDepartList;
        // }
        if (taskName.indexOf('接收方部门/团队领导审批') >= 0) {
          //newStoreDepartmentID
          return newStoreDepartmentPosList;
        }
        if (taskName.indexOf('移交方资产部专责审批') >= 0) {
          return relAssetOriginalPosList;
        }
        if (taskName.indexOf('移交方部门/团队领导审批') >= 0) {
          // originalStoreDepartmentID
          return originStoreDepartmentPosList;
        }
      }

      /***
       * 资产信息变更"100199031021"
       */
      if (businessInfoObj?.businessType == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1021`) {
        if (taskName.indexOf('部门资产管理员审核') >= 0) {
          return dutyDepartList;
        }
        if (taskName.indexOf('单位资产管理员复核') >= 0) {
          return businessPosList;
        }
      }

      //资产公共使用
      if (taskName.indexOf('部门/团队资管员审批') >= 0) {
        return dutyDepartList;
      }

      if (taskName.indexOf('处长或专责') >= 0 && taskName.indexOf('归口') < 0 && taskName.indexOf('部门') < 0) {
        return ownPosList;
      }

      if (
        taskName.indexOf('本单位归口管理部门领导') >= 0 ||
        (taskName.indexOf('内部会签') >= 0 && taskName.indexOf('归口') >= 0 && taskName.indexOf('本单位') >= 0)
      ) {
        return relPosList;
      }

      if (
        (taskName.indexOf('处长或专责') >= 0 && taskName.indexOf('归口') >= 0 && taskName.indexOf('相关') < 0) ||
        (taskName.indexOf('内部会签') >= 0 && taskName.indexOf('归口') >= 0) ||
        taskName.indexOf('归口部门领导') >= 0 ||
        taskName.indexOf('归口管理部门处长') >= 0 ||
        taskName.indexOf('归口管理部门领导') >= 0
      ) {
        return busPosList;
      }

      if ((taskName.indexOf('处长或专责') >= 0 && taskName.indexOf('归口') < 0 && taskName.indexOf('相关') >= 0) || taskName.indexOf('相关部门领导') >= 0) {
        return relPosList;
      }

      if (taskName.indexOf('内部会签') >= 0 || taskName.indexOf('重点项目负责人') >= 0 || taskName.indexOf('部门/团队领导') >= 0) {
        return dutyDepartList;
      }

      return '';
    };

    /**根据个人岗位获取机构 */
    const [ownPosList, setOwnPosList] = useState<Record<string, any>[]>([]);
    /**根据当前人岗位所在部门id获取机构 */
    const [dutyDepartList, setDutyDepartList] = useState<Record<string, any>[]>([]);
    /**根据归口部门获取机构 */
    const [busPosList, setBusPosList] = useState<Record<string, any>[]>([]);
    /**根据相关部门获取机构 */
    const [relPosList, setRelPosList] = useState<Record<string, any>[]>([]);
    /**根据本单位获取机构 */
    const [businessPosList, setBusinessPosList] = useState<Record<string, any>[]>([]);

    /**资产中 */
    const [relAssetDepartmentPosList, setRelAssetDepartmentPosList] = useState<Record<string, any>[]>([]);
    const [relAssetOriginalPosList, setRelAssetOriginalPosList] = useState<Record<string, any>[]>([]);
    const [newStoreDepartmentPosList, setNewStoreDepartmentPosList] = useState<Record<string, any>[]>([]);
    const [originStoreDepartmentPosList, setOriginStoreDepartmentPosList] = useState<Record<string, any>[]>([]);
    const [belongDepartmentPosList, setBelongDepartmentPosList] = useState<Record<string, any>[]>([]);

    /**
     * 采购  consignDepartmentID  platformDepartmentID
     */
    const [consignDepartmentPosList, setConsignDepartmentPosList] = useState<Record<string, any>[]>([]);
    const [platformDepartmentPosList, setPlatformDepartmentPosList] = useState<Record<string, any>[]>([]);
    const [theCompanyPosList, setTheCompanyPosList] = useState<Record<string, any>[]>([]); //本公司下的岗位

    useEffect(() => {
      getDutyPosTreeRun({
        params: 1,
        flowType: null,
        orgID: getUserDutyDepID(),
      });
    }, [getUserDutyDepID()]);

    useEffect(() => {
      getOwnPosTreeRun({
        params: 2,
        flowType: 3,
        orgID: getPosIDs(),
      });
    }, [getPosIDs()]);

    useEffect(() => {
      if (businessInfoObj.busiDepartmentID) {
        getBusPosTreeRun({
          params: 1,
          flowType: 'null',
          orgID: businessInfoObj.busiDepartmentID,
        });
      }
    }, [businessInfoObj.busiDepartmentID]);

    useEffect(() => {
      if (businessInfoObj.relateDepartmentID) {
        getPosTreeRun({
          params: 1,
          flowType: 'null',
          orgID: businessInfoObj.relateDepartmentID,
        });
      }
    }, [businessInfoObj.relateDepartmentID]);

    /**资产中 */
    // if (requestController == 'assetApplyAllot') {
    useEffect(() => {
      if (businessInfoObj.newDepartmentID) {
        getAssetDepartmentPosTreeRun({
          params: 1,
          flowType: 'null',
          orgID: businessInfoObj.newDepartmentID,
        });
      }
    }, [businessInfoObj.newDepartmentID]);

    useEffect(() => {
      if (businessInfoObj.originalStoreCompanyID) {
        getAssetOriginalPosTreeRun({
          params: 1,
          flowType: 'null',
          orgID: businessInfoObj.originalStoreCompanyID,
        });
      }
    }, [businessInfoObj.originalStoreCompanyID]);
    // }

    useEffect(() => {
      if (businessInfoObj.newStoreDepartmentID) {
        getNewStoreDepartmentPosTreeRun({
          params: 1,
          flowType: 'null',
          orgID: businessInfoObj.newStoreDepartmentID,
        });
      }
    }, [businessInfoObj.newStoreDepartmentID]);

    useEffect(() => {
      if (businessInfoObj.originalStoreDepartmentID) {
        getOriginalStoreDepartmentPosTreeRun({
          params: 1,
          flowType: 'null',
          orgID: businessInfoObj.originalStoreDepartmentID,
        });
      }
    }, [businessInfoObj.originalStoreDepartmentID]);

    useEffect(() => {
      if (businessInfoObj.belongDepartmentID) {
        getBelongDepartmentPosTreeRun({
          params: 1,
          flowType: 'null',
          orgID: businessInfoObj.belongDepartmentID,
        });
      }
    }, [businessInfoObj.belongDepartmentID]);

    // useEffect(() => {
    //   /** 职能部门月度计划采购申请审批流程  业务归口部门专责审核 + 业务归口部门领导审批 */
    //   if (businessInfoObj.consignDepartmentID) {
    //     getConsignDepartmentPosTreeRun({
    //       params: 1,
    //       flowType: 'null',
    //       orgID: businessInfoObj.consignDepartmentID,
    //     });
    //   }
    // }, [businessInfoObj.consignDepartmentID]);

    // useEffect(() => {
    //   /** 科研团队月度计划采购申请审批流程  平台归口管理部门审批 + 平台归口管理部门领导审批 */
    //   if (businessInfoObj.platformDepartmentID) {
    //     getPlatformDepartmentPosTreeRun({
    //       params: 1,
    //       flowType: 'null',
    //       orgID: businessInfoObj.platformDepartmentID,
    //     });
    //   }
    // }, [businessInfoObj.platformDepartmentID]);

    // useEffect(() => {
    //   /**获取本公司下的岗位 */
    //   getTheCompanyPosTreeRun({
    //     params: 1,
    //     flowType: null,
    //     orgID: getCompanyID(),
    //   });

    //   // if (getCompanyID() != '1') {
    //   //   /**获取怀柔实验室下的岗位 */
    //   //   getBUPosTreeRun({
    //   //     params: 0,
    //   //     flowType: null,
    //   //     orgID: 1,
    //   //   });
    //   // }
    // }, [getCompanyID()]);

    /**
     *
     * @param data 获取岗位树的所有id
     * @returns
     */
    const getTreeIdList = (data) => {
      let arr: any = [];
      const getTreeId = (list) => {
        list.forEach((item) => {
          arr.push(item.id);
          if (item.children) getTreeId(item.children);
        });
      };
      getTreeId(data);
      return arr;
    };

    /**
     * 流程节点回调
     * @param res
     */
    const taskNodesCallBack = (res: any) => {
      if (res && res?.msgFlag) {
        if (res?.obj && res?.obj?.length > 0) {
          let postIDs: string[] | any = []; //保存所有岗位 id
          postIDs.push(
            ...getTreeIdList(ownPosList),
            ...getTreeIdList(busPosList),
            ...getTreeIdList(relPosList),
            ...getTreeIdList(dutyDepartList),
            ...getTreeIdList(businessPosList),
            ...getTreeIdList(theCompanyPosList),
            ...getTreeIdList(relAssetDepartmentPosList),
            ...getTreeIdList(relAssetOriginalPosList),
            ...getTreeIdList(newStoreDepartmentPosList),
            ...getTreeIdList(originStoreDepartmentPosList),
            ...getTreeIdList(belongDepartmentPosList),
            ...getTreeIdList(consignDepartmentPosList),
            ...getTreeIdList(platformDepartmentPosList),
          );

          /**
           * 处理数据
           * @param dataList
           * @returns
           */
          let loopMapPost = (dataList: Record<string, any>[]) => {
            return dataList?.map((item: any, index: number) => {
              const { postDateList, postDateKeys, newUserList, posTreeData } = handlePostList(item, index);
              postIDs?.push(...postDateKeys);
              return {
                ...item,
                postValues: postDateList,
                allUserValues: newUserList,
                posTreeData: posTreeData,
              };
            });
          };
          const postUserList = loopMapPost(res?.obj); // 返回的数据 没有 objJson
          setWorkFlowNodes(postUserList);

          let removalPosts = Array.from(new Set(postIDs)); //去重 岗位 id
          if (removalPosts && removalPosts?.length > 0) {
            const poskeys: any = removalPosts?.filter((item: any) => item);
            let postIDsStr: string = poskeys?.toString();
            loadUserRun(postIDsStr);
          }
        }
      }

      setFlowNodesLoading(false);
    };

    /**
     * 流程节点
     */
    const { taskNodesRun, taskNodesLoading } = getTaskNodes(taskNodesCallBack, requestController);

    /**
     * 流程列表接口回调
     * @param res
     */
    const procdefDataCallback = async (res: any) => {
      if (businessInfoObj?.businessType == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1021`) {
        await getBUPosTreeRun({
          params: 0,
          flowType: null,
          orgID: 1,
        });
      }

      if (businessCategory?.indexOf(`${getTenantID()}${ILoadMapTypeAll.PURAPPLY_APPLY}`) > -1) {
        await getBUPosTreeRun({
          params: 0,
          flowType: null,
          orgID: 1,
        });
        /**获取本公司下的岗位 */
        await getTheCompanyPosTreeRun({
          params: 1,
          flowType: null,
          orgID: getCompanyID(),
        });
        /** 职能部门月度计划采购申请审批流程  业务归口部门专责审核 + 业务归口部门领导审批 */
        if (businessInfoObj.consignDepartmentID) {
          await getConsignDepartmentPosTreeRun({
            params: 1,
            flowType: 'null',
            orgID: businessInfoObj.consignDepartmentID,
          });
        }
        if (businessInfoObj.platformDepartmentID) {
          await getPlatformDepartmentPosTreeRun({
            params: 1,
            flowType: 'null',
            orgID: businessInfoObj.platformDepartmentID,
          });
        }
      }

      if (res && res?.msgFlag) {
        if (res && res?.rows && res?.rows?.length > 0) {
          let nodeParams: Record<string, any> = {
            businessID: businessInfoObj?.id, //业务工单ID
          };
          let dataDefaultObj: Record<string, any> | any = res?.rows?.find((item: any) => {
            return item.isDefault == '1';
          });
          if (dataDefaultObj && dataDefaultObj?.id) {
            nodeParams['processID'] = dataDefaultObj?.id; //流程ID
          } else {
            nodeParams['processID'] = res?.rows?.[0]?.id;
          }

          changeProcessID(nodeParams['processID']);

          setFlowNodesLoading(true);
          taskNodesRun(nodeParams);
        }
      } else {
        message.error(res?.msg);
      }
    };

    /**
     * 获取流程列表
     */
    const { getProcdefData, pageLoading } = procdefDataGridServices(procdefDataCallback, requestController);

    /**
     * 处理岗位 和接口中的人员挂钩
     */
    const handPostAndUserList = (curItemObj: Record<string, any>, postList: Record<string, any>[]) => {
      let newPostList: Record<string, any>[] = [];
      postList?.forEach((postItem: Record<string, any>) => {
        newPostList?.push({
          ...postItem,
          checkUserList: curItemObj?.taskIsSign == 0 ? null : loadUserData?.[postItem?.postId],
        });
      });
      return newPostList;
    };

    /**
     * 保保存 普通节点id 对饮选中 的岗位
     */
    const [ordinaryUserInfoObj, setOrdinaryUserInfoObj] = useState<Record<string, any>>({});

    /**
     * 岗位和人员节点处理
     */
    const workFlowNodesListMemo = useMemo(() => {
      let nodesList: Record<string, any>[] = [];
      if (workFlowNodes && workFlowNodes?.length > 0 && loadUserData && JSON.stringify(loadUserData) != '{}') {
        let postCheckInfo: Record<string, any> = {}; //保存 普通节点id 对饮选中 的岗位

        workFlowNodes?.forEach((pItem: any, pIndex: number) => {
          nodesList[pIndex] = {
            ...pItem,
            postValues: pItem?.dealPositionID == 'originPositionID,' ? pItem?.postValues : handPostAndUserList(pItem, pItem?.postValues),
          };
          if (pItem?.dealPositionID != 'originPositionID,' && pItem?.taskIsSign == 0) {
            const checkPostIdObj = pItem?.taskNode;
            postCheckInfo[checkPostIdObj] = pItem?.postValues?.[0]?.postId;
          }
        });

        setOrdinaryUserInfoObj(postCheckInfo);
      }
      return nodesList;
    }, [workFlowNodes, loadUserData]);

    /** 初始化 */
    useEffect(() => {
      if (!businessInfoObj?.id) return;
      if (switchFlowObj?.processID) {
        let nodeParams: Record<string, any> = {
          businessID: businessInfoObj?.id, //业务工单ID
          processID: switchFlowObj?.processID,
        };
        taskNodesRun(nodeParams);
      } else {
        const { mpositionList } = getPersonalInfo();
        let deptFlag = '';
        let companyID = '';
        mpositionList.map((item) => {
          if (item.id == getPosIDs()) {
            deptFlag = item.deptFlag;
            companyID = item.companyID;
          }
        });
        let params: Record<string, any> = {
          orderType: orderType, //工单类型
          category: category, //业务流程类别
          businessCategory: businessCategory, // 总 流程类别
          pageSize: 1000,
          current: 1,
          suspendState: '1',
          ownCompanyID: companyID,
          deptFlag,
        };

        if (workFlowName) {
          params['name'] = workFlowName;
        }

        getProcdefData(params);
      }
    }, [switchFlowObj?.processID, businessInfoObj?.id]);

    /** 导出Ref 数据 */
    useImperativeHandle(ref, () => ({
      workflowNodesList: workFlowNodesListMemo,
      workFlowNodes: workFlowNodes,
    }));

    return (
      <Spin spinning={loadUserLoading || taskNodesLoading || pageLoading}>
        {workFlowNodesListMemo && workFlowNodesListMemo?.length > 0 ? (
          <WorkflowNodesTable
            workFlowNodesList={workFlowNodesListMemo}
            userDataInfoObj={loadUserData}
            ordinaryUserInfoObj={ordinaryUserInfoObj}
            changePostCheckID={(selectKey: string, selectValue: string) => {
              let changePostIdInfo: Record<string, any> = _.cloneDeep(ordinaryUserInfoObj);
              changePostIdInfo[selectKey] = selectValue;
              setOrdinaryUserInfoObj(changePostIdInfo);
            }}
          />
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无流程节点信息！" />
        )}
      </Spin>
    );
  },
);
